﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Community.IMode;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Model;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.IService;

namespace FantastPlatform.Community.UI.Service
{
    public partial class WorkLog : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IWorkLogService wlService = ServiceFactory.CreateService<IWorkLogService>();

            switch (Action)
            {
                case "Add":
                    string data = Data;
                    WorkLogView view = (WorkLogView)JsonToEntity<WorkLogView>(RepairString(data));
                    IWorkLog worklog = new FantastPlatform.Community.Model.WorkLog();

                    if (view != null)
                    {
                        worklog.Id = view.Id;
                        //worklog.Name = view.Title;
                        //worklog.Title = view.Title;
                        worklog.Content = view.Content;
                        worklog.IsPrompt = view.IsPrompt;
                        worklog.PromptTime = view.PromptTime;
                        worklog.CreateDate = System.DateTime.Now;
                        worklog.PoliceMan = LoginEmployee;
                        //worklog.PoliceMan = new Employee();
                        //worklog.PoliceMan.Id = 568;
                        worklog.Code = "001";
                    }
                    worklog.Enable = true;
                    if (worklog.Id == 0)
                    {
                        worklog.CreateDate = System.DateTime.Now;
                        wlService.Create(worklog);
                        ReturnSuccessMessage("日志保存成功");
                    }
                    else
                    {
                        worklog.ModifyDate = System.DateTime.Now;
                        wlService.Update(worklog);
                        ReturnSuccessMessage("日志更新成功");
                    }
                    break;
                case "Search":
                    int total;
                    object[] wl;
                    ConditionGroup group = new ConditionGroup();
                 IOrganization org ;
                    Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
                    group.Conditions.Add(enableCondition);
                    if (LoginEmployee != null)
                    {
                        org = (from o in LoginEmployee.EmployeePosts
                                                where o.Enable =true
                                                select o.Post.Organization).FirstOrDefault();
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = org.Id });
                            }
                            else
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                            }
                        }
                    }
                    IList<IWorkLog> list = wlService.Search(group, null, PageSize, SelfPage, out total);
                    wl = (from p in list
                          select new
                        {
                            Id = p.Id,
                            //Code = p.Code,
                            //Title = p.Title,
                            Content = p.Content,
                            CreateDate = p.CreateDate.ToString(),
                            Desciption = p.Description,
                            IsPrompt = p.IsPrompt,
                            PromptTime = p.PromptTime.ToString(),
                            PoliceMan = p.PoliceMan.Name,
                            MessageCount = GetRelyListByLogId(p.Id, Int32.MaxValue, 1, out  total).Count

                        }).OrderByDescending(p => p.IsPrompt).ThenBy(p => p.Id).ToArray();
                    ReturnList(total, wl);
                    break;
                case "SearchPrompt":
                    group = new ConditionGroup();
                    enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
                    Condition condition1 = new Condition() { Type = typeof(bool).FullName, Field = "IsPrompt", Value1 = true, Relation = Relations.And };
                    Condition condition2 = new Condition() { Type = typeof(int).FullName, Field = "PoliceMan.Id", Value1 = LoginEmployee.Id, Relation = Relations.And };
                    group.Conditions.Add(enableCondition);
                    group.Conditions.Add(condition1);
                    group.Conditions.Add(condition2);
                    list = wlService.Search(group, null, PageSize, SelfPage, out total);
                    wl = (from p in list
                          where p.PromptTime > DateTime.Now
                          select new
                        {
                            Id = p.Id,
                            //Title = p.Title,
                            Content = p.Content,
                            CreateDate = p.CreateDate.ToString(),
                            Desciption = p.Description,
                            IsPrompt = p.IsPrompt,
                            PromptTime = p.PromptTime.ToString(),
                            PoliceMan = p.PoliceMan.Name,
                            MessageCount = GetRelyListByLogId(p.Id, Int32.MaxValue, 1, out  total).Count
                        }).OrderByDescending(p => p.IsPrompt).ThenBy(p => p.Id).ToArray();

                    ReturnList(wl.Length, wl);
                    break;
                case "SearchByCondition":
                    view = (WorkLogView)JsonToEntity<WorkLogView>(RepairString(Data));
                    int searchTotal;
                    ConditionGroup groupw = new ConditionGroup();
                    groupw.Conditions.Add(new Condition { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
                    org = LoginEmployee.EmployeePosts[0].Post.Organization;
                    if (LoginEmployee != null)
                    {
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                groupw.Conditions.Add(new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = org.Id });
                            }
                            else
                            {
                                groupw.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                            }
                        }
                    }
                    //if (!string.IsNullOrEmpty(view.Title))
                    //{
                    //    Condition wlsearchT = new Condition() { Field = "Title", Type = typeof(string).FullName, Value1 = view.Title + "%", Comparison = Comparisons.Like, Relation = Relations.And };
                    //    groupw.Conditions.Add(wlsearchT);
                    //}
                    if (!string.IsNullOrEmpty(view.PoliceMan))
                    {
                        Condition wlsearchP = new Condition() { Field = "PoliceMan.Id", Type = typeof(Int32).FullName, Value1 = view.PoliceMan, Comparison = Comparisons.Like, Relation = Relations.And };
                        groupw.Conditions.Add(wlsearchP);
                    }
                    if (!string.IsNullOrEmpty(view.Name))
                    {
                        Condition wlsearchN = new Condition() { Field = "Name", Type = typeof(string).FullName, Value1 = view.Name + "%", Comparison = Comparisons.Like, Relation = Relations.And };
                        groupw.Conditions.Add(wlsearchN);
                    }
                    if (view.OrganizationId != 0)
                    {
                        Condition wlsearchN = new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Id", Type = typeof(Int32).FullName, Value1 = view.OrganizationId, Relation = Relations.And };
                        groupw.Conditions.Add(wlsearchN);
                    }
                    IList<IWorkLog> wls = wlService.Search(groupw, null, PageSize, SelfPage, out searchTotal);
                    object[] objsearch = (from w in wls
                                          select new
                                          {
                                              Id = w.Id,
                                              Name = w.Name,
                                              IsPrompt = w.IsPrompt,
                                              PromptTime = w.PromptTime.ToString(),
                                              //Code = w.Code,
                                              //Title = w.Title,
                                              Content = w.Content,
                                              CreateDate = w.CreateDate.ToString(),
                                              PoliceMan = w.PoliceMan.Name,

                                          }).OrderByDescending(w => w.IsPrompt).ThenBy(w => w.Id).ToArray();
                    ReturnList(searchTotal, objsearch);
                    break;
                case "Get":
                    worklog = wlService.Get(Id);
                    object wlobj = new
                    {
                        Id = worklog.Id,
                        IsPrompt = worklog.IsPrompt.ToString().ToLower(),
                        PromptTime = worklog.PromptTime,
                        PoliceMan = worklog.PoliceMan.Name,
                        //Title = worklog.Title,
                        Content = worklog.Content,
                        CreateDate = worklog.CreateDate,
                        Name = worklog.Name
                    };
                    if (wlobj == null)
                    {
                        return;
                    }
                    string jsonStr = JsonConvert.SerializeObject(wlobj, Formatting.Indented, new JavaScriptDateTimeConverter());
                    jsonStr = "{ 'success': 'true', 'data': " + jsonStr + "}";

                    Response.Write(jsonStr);
                    Response.End();
                    break;
                case "GetInfo":
                    worklog = wlService.Get(Id);
                    wlobj = new
                    {
                        Id = worklog.Id,
                        IsPrompt = worklog.IsPrompt.ToString().ToLower(),
                        PromptTime = worklog.PromptTime,
                        PoliceMan = worklog.PoliceMan.Name,
                        //Title = worklog.Title,
                        Content = worklog.Content,
                        CreateDate = worklog.CreateDate.ToString(),
                        Name = worklog.Name
                    };
                    ReturnObj(wlobj);
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的设备信息ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    wlService.Delete(idList);
                    ReturnSuccessMessage("删除成功");
                    break;
                case "GetPrompt":
                    object[] objList = new object[2] { new { Name = "是", Value = "true" }, new { Name = "否", Value = "false" } };
                    ReturnList(2, objList);
                    break;
                case "GetOrganization":
                    groupw = new ConditionGroup();
                    groupw.Conditions.Add(new Condition { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
                    org = LoginEmployee.EmployeePosts[0].Post.Organization;
                    objList = null;
                    if (LoginEmployee != null)
                    {
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                                objList = (from o in org.Children
                                           where o.Name.EndsWith("派出所")
                                           select new
                                           {
                                               Id = o.Id,
                                               Name = o.Name
                                           }
                                ).ToArray();
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                objList = (from o in org.Children
                                           where o.Name.EndsWith("责任区")
                                           select new
                                           {
                                               Id = o.Id,
                                               Name = o.Name
                                           }
                               ).ToArray();
                            }
                            else
                            {
                                objList = new object[1] { new { Id = org.Id, Name = org.Name } };
                            }
                        }
                    }
                    ReturnList(objList.Length, objList);
                    break;
                case "GetPoliceByOrgId":

                    groupw = new ConditionGroup();
                    groupw.Conditions.Add(new Condition { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
                    int orgId = Id;
                    if (orgId == 0)
                    {
                        orgId = LoginEmployee.EmployeePosts[0].Post.Organization.Id;
                    }
                    groupw.Conditions.Add(new Condition() { Field = "EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = orgId });
                    IList<IEmployee> emList = ServiceFactory.CreateService<IEmployeeService>().Search(groupw, null, Int32.MaxValue, 1, out total);
                    objList = (from em in emList
                               select new
                               {
                                   Id = em.Id,
                                   Name = em.Name
                               }
                               ).ToArray();
                    ReturnList(total, objList);
                    break;
                case "GetReplyByLogId":
                    int workLogId = Id;
                    IList<IWorkLogReply> replyList = GetRelyListByLogId(workLogId, PageSize, SelfPage, out  total);
                    objList = (from o in replyList
                               select new
                               {
                                   Id = o.Id,
                                   Content = o.Content,
                                   ReplyDate = o.CreateDate.ToString(),
                                   PoliceMan = o.PoliceMan.Name
                               }).ToArray();
                    ReturnList(total, objList);
                    break;

            }

        }

        private IList<IWorkLogReply> GetRelyListByLogId(int workLogId, int PageSize, int SelfPage, out int totalCount)
        {
            IWorkLogReplyService logReplyService = ServiceFactory.CreateService<IWorkLogReplyService>();
            Condition workLogCondition = new Condition() { Field = "WorkLog.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = workLogId };
            ConditionGroup workLogReplyGroup = new ConditionGroup();
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            workLogReplyGroup.Conditions.Add(enableCondition);
            workLogReplyGroup.Conditions.Add(workLogCondition);
            IList<IWorkLogReply> replyList = logReplyService.Search(workLogReplyGroup, null, PageSize, SelfPage, out totalCount);
            return replyList;
        }
        public class WorkLogView
        {
            public int Id { get; set; }
            //public string Title { get; set; }
            public string Content { get; set; }
            public bool IsPrompt { get; set; }
            public DateTime? PromptTime { get; set; }
            public string PoliceMan { get; set; }
            public string Name { get; set; }
            public int OrganizationId { get; set; }
        }
    }
}